package com.emp.web;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.emp.bean.User;
import com.emp.service.UserService;
import com.emp.util.MyRealm;

@Controller
@RequestMapping("/user")
public class UserController {
	 @Resource
     private UserService userService;	 
	 

	 @RequestMapping("/toLogin")
	 public String toLogn(){
		  return "Login";
	 }
	 
	 @RequestMapping("/login")
	 public String login(User user,HttpServletRequest request){
		 //spring容器自动帮我们做的
		// SecurityUtils.setSecurityManager(securityManager);
		//获取当前用户
			Subject subject=SecurityUtils.getSubject();
			UsernamePasswordToken token
			      =new UsernamePasswordToken(user.getUsername(), user.getPassword());
			try{
				//为当前用户进行认证，授权
				subject.login(token);
				
				//request.setAttribute("user", user);
				return "Success";
				
			}catch(Exception e){
				e.printStackTrace();
				request.setAttribute("errorMsg", "用户名或密码错误！");
				return "Login";
			}

	 }
	 
	 @RequestMapping("/toRegister")
	 public String toRegister(){
		 return "Register";
	 }
	 
	 @RequestMapping("/register")
	 public String register(String username,String password) throws Exception{
		   userService.doRegister(username, password);
		   return "Success";
	 }
}
